/**
 * Created by Will Bean on 2016/8/21.
 */
import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import SelectInput from './SelectInput'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL ,getAuthShop} from '../publicAPI/publicAPI'

class ShopServiceM extends Component {

    constructor (props, context) {
        super(props, context);
        console.log("初始化");

        this.state = {
            delete: false,
            deleteId : -1,
            serviceList : [],
            currentShopId : 1,
            storeList: [],
            ddServiceList : [],
            hasBeenMounted : false
        } ;// 初始化状态
    }

    getStoreNameList(){
        var arr = [];
        this.state.storeList.map((store,index)=>{
            arr.push((<option key={index} value={store.id}>{store.dname}</option>))
        });
        return arr;
    }

    handleSelectChange(val){
        var _this = this;
        fetch(ROOTURL+'serv/shop/aggregated/search.api',{
            method: 'POST',
            body: JSON.stringify({
                "where": {"shopId": [["eq", val]],"dd":[["eq", false]]},
                "order": [["id","asc"]]
            })
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    _this.setState({
                        serviceList:data
                    })
                })
            }
        });
        fetch(ROOTURL+'serv/shop/search.api',{
            method: 'POST',
            body: JSON.stringify({
                "where": {"shopId": [["eq", val]],"dd":[["eq", true]]},
                "order": [["id","asc"]]
            })
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    _this.setState({
                        ddServiceList:data
                    })
                })
            }
        })
    }

    componentWillMount() {
        console.log("将安装");
        if(!this.state.hasBeenMounted){
            this.setState({hasBeenMounted:true});
            var url = ROOTURL + 'shop/search.api';//获取门店列表，用以门店选择器
            var _this = this;
            getAuthShop({
                "where": {"dd":[["eq", false]]},
                "order": [["id","asc"]]
            },function (data) {
                var shopId = _this.props.params.id ? _this.props.params.id : data[0].id;
                fetch(ROOTURL+'serv/shop/aggregated/search.api',{
                    method: 'POST',
                    body: JSON.stringify({
                        "where": {"shopId": [["eq", shopId]],"dd":[["eq", false]]},
                        "order": [["id","asc"]]
                    })
                }).then(res=>{
                    if(res.ok){
                        res.json().then(data=>{
                            _this.setState({
                                serviceList:data
                            })
                        })
                    }
                });
                fetch(ROOTURL+'serv/shop/aggregated/search.api',{
                    method: 'POST',
                    body: JSON.stringify({
                        "where": {"shopId": [["eq", shopId]],"dd":[["eq", true]]},
                        "order": [["id","asc"]]
                    })
                }).then(res=>{
                    if(res.ok){
                        res.json().then(data=>{
                            _this.setState({
                                ddServiceList:data
                            })
                        })
                    }
                });
                _this.setState({
                    storeList: data,
                    currentShopId: shopId
                })
            })
            // fetch(url, {
            //     method: 'POST',
            //     mode: 'cors',
            //     body : JSON.stringify({
            //         "where": {"dd":[["eq", false]]},
            //         "order": [["id","asc"]]
            //     })
            // }).then(response => {
            //     if (response.ok){
            //         response.json().then(function (data) {
            //             var shopId = _this.props.params.id ? _this.props.params.id : data[0].id;
            //             fetch(ROOTURL+'serv/shop/aggregated/search.api',{
            //                 method: 'POST',
            //                 body: JSON.stringify({
            //                     "where": {"shopId": [["eq", shopId]],"dd":[["eq", false]]},
            //                     "order": [["id","asc"]]
            //                 })
            //             }).then(res=>{
            //                 if(res.ok){
            //                     res.json().then(data=>{
            //                         _this.setState({
            //                             serviceList:data
            //                         })
            //                     })
            //                 }
            //             });
            //             fetch(ROOTURL+'serv/shop/aggregated/search.api',{
            //                 method: 'POST',
            //                 body: JSON.stringify({
            //                     "where": {"shopId": [["eq", shopId]],"dd":[["eq", true]]},
            //                     "order": [["id","asc"]]
            //                 })
            //             }).then(res=>{
            //                 if(res.ok){
            //                     res.json().then(data=>{
            //                         _this.setState({
            //                             ddServiceList:data
            //                         })
            //                     })
            //                 }
            //             });
            //             _this.setState({
            //                 storeList: data,
            //                 currentShopId: shopId
            //             })
            //         })
            //     }
            // }).catch(function (error) {
            //     console.log('Request failed', error);
            // });
        }

    }

    componentDidMount() {
        console.log("安装成功")
    }

    handleDelete(id){
        this.setState({
            delete: !this.state.delete,
            deleteId : id
        })
    }

    changeToMin(ms){
        return parseInt(ms/60000)
    }

    handleStoreDelete(){
        var url = ROOTURL + 'serv/shop/instance.api?id='+this.state.deleteId;
        this.setState({
            delete: !this.state.delete
        });
        fetch(url, {
            method : 'delete',
            // mode : 'no-cors',
            body: JSON.stringify({})
        }).then(res=>{
            if(res.ok){
                res.json().then(data=>{
                    location.href = '/ShopServiceM'+ this.state.currentShopId
                })
            }
        });
    }

    //render thead
    tHead() {
        var data = [
            {name: "id"},
            {name: "图标"},
            {name: "标识"},
            {name: "显示名"},
            {name: "基础价格"},
            {name: "服务时长"},
            {name: "并行工作荷载"},
            {name: "扩展于"},
            {name: "操作"}
        ];
        const _headArr = [];
        const _width = {
            "0" : "5%",
            "1" : "5%",
            "2" : "10%",
            "3" : "10%",
            "4" : "10%",
            "5" : "10%",
            "6" : "10%",
            "7" : "20%",
            "8" : "20%"
        };
        //_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
        return _headArr;
    }

    tBody(dataList,deleteBtn) {

        return dataList.map(item => <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.meta && item.meta.icon ? <img style={{maxWidth: '50px',maxHeight:'50px',verticalAlign:'middle'}} src={ROOTURL + 'asset/images/get.api?hashed=' + item.meta.icon}/> : null}</td>
            <td>{item.name}</td>
            <td>{item.dname}</td>
            <td>{item.cost0}</td>
            <td>{this.changeToMin.bind(this)(item.duration)}</td>
            <td>{item.workload}</td>
            <td>{item.meta.prototypeServiceName}</td>
            <td>
                <span><NavLink  to={`/ShopServiceM/ShopServiceEditor/${item.id}`} className="rbtn green">编辑</NavLink></span>
                {deleteBtn ? <span style={{marginLeft: "15px"}}><a  className="rbtn red" onClick={()=>this.handleDelete(item.id)}>删除</a></span> : null }
                <span style={{marginLeft: "15px"}}><NavLink  to={`/ShopServiceM/ShopServiceEditor${'Preview'}/${item.id}`} className="rbtn green">预览</NavLink></span>
            </td>
        </tr>)
    }

    render() {console.log("服务原型" + "渲染" + this.state.page);
        console.log(this.state)
        return (
            <div className="right-wapper " style={{height:'auto'}}>
                <div className="rt-wrap">
                    <h2 className="catagory">
                        <Link to={`/PrototypeServiceM`}><span className={style['cata-title']}>服务原型</span></Link>
                        <Link to={`/ShopServiceM`}><span className={style['cata-title-current']}>门店服务类型</span></Link>
                        <Link to={`/BarberServiceM`}><span className={style['cata-title']}>理发师服务类型</span></Link>
                        <Link to={`/ShopServiceM/${this.state.currentShopId}`}>
                            <button className="add-btn" />
                        </Link>
                    </h2>
                    <div style={{margin:'10px 0'}}>
                        <label style={{paddingRight:'10px'}}>门店选择器</label>{console.log(this.getStoreNameList())}
                        <SelectInput optionsData={this.getStoreNameList()}
                                     val={this.state.currentShopId}
                                     onChange={val=>{this.setState({currentShopId:val});
                                     this.handleSelectChange.bind(this)(val)
                                     }}/>
                    </div>
                    <div style={{margin:'20px 0 10px'}}>
                        <label>当前提供的服务项目</label>
                    </div>
                    <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)(this.state.serviceList,true)} />
                    {this.state.ddServiceList.length ? (<div>
                    <div style={{margin:'30px 0 10px'}}>
                        <label>停止运营的服务项目</label>
                    </div>
                    <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)(this.state.ddServiceList,false)} /></div> ): null}
                </div>
                { this.state.delete ?
                    <div id={style.msgDialog}>
                        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
                            <div className={style['msgDialog_button']}>
                                <button id={style['msgDialog_yes']} onClick={this.handleStoreDelete.bind(this)}>确定</button>
                                <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
                            </div>
                        </div>
                    </div> : null}
            </div>
        )
    }
}

export default ShopServiceM
